package main

import "fmt"

func main() {
	// slice2Func()
	// slice3Func()
	// slice4Func()
	slice5Func()
	slice6Func()
}

func slice1Func() {
	// 1. 声明
	var s1 []int
	if s1 == nil {
		fmt.Println("s1 is nil")
	} else {
		fmt.Println("s1 is not nil")
	}
	// :
	s2 := []int{1, 2, 3}
	// make 初始化
	var s3 []int = make([]int, 3)
	fmt.Println(s2, s3)
	// 初始化赋值
	var s4 []int = make([]int, 4, 4)
	fmt.Println(s4)
	s5 := []int{1, 2, 3}
	fmt.Println(s5)
	// 从数组切片
	arr := []int{4, 5, 6}
	var s6 []int
	s6 = arr[1:2]
	fmt.Println(s6)
}

// 通过make来创建切片
func slice2Func() {
	var slice0 []int = make([]int, 10)
	var slice1 = make([]int, 10)
	var slice2 = make([]int, 10, 10)
	fmt.Printf("make全局slice0 ：%v\n", slice0)
	fmt.Printf("make全局slice1 ：%v\n", slice1)
	fmt.Printf("make全局slice2 ：%v\n", slice2)
}

// 可直接创建 slice 对象，自动分配底层数组。
func slice3Func() {
	s4 := []int{1, 2, 3, 5: 100}
	fmt.Println(s4, len(s4), cap(s4))
	s5 := [][]int{
		[]int{1, 2, 3},
		[]int{11, 21, 31},
		[]int{12, 22, 32},
	}
	fmt.Println(s5)
}
func slice4Func() {
	a := [5]struct {
		x int
	}{}
	s := a[:]
	a[1].x = 10
	s[2].x = 20
	fmt.Println(a)
	fmt.Printf("%p, %p\n", &a, &a[0])
}

// append
func slice5Func() {
	var a = []int{1, 2, 3}
	fmt.Printf("slice a :%v\n", a)
	var b = []int{4, 5, 6}
	fmt.Printf("slice b :%v\n", b) // slice b :[4 5 6]
	c := append(a, b...)           // a 加到 b
	fmt.Printf("slice c :%v\n", c) // slice c :[1 2 3 4 5 6]
	d := append(c, 7)
	fmt.Printf("slice d :%v\n", d) // slice d :[1 2 3 4 5 6 7]

	s1 := make([]int, 0, 5)
	fmt.Printf("%p\n", &s1)
	s2 := append(s1, 1)
	fmt.Printf("slice s2 :%p\n", &s2)
	fmt.Println(s1, s2) // [] [1]

}

// 切片拷贝
func slice6Func() {
	s1 := []int{1, 2, 3, 4, 5}
	fmt.Printf("slice s1 :%v\n", s1)
	s2 := make([]int, 10)
	fmt.Printf("slice s2 :%v\n", s2)
	copy(s2, s1) // 把s1 copy 到 s2
	fmt.Printf("copied slice s1 :%v\n", s1)
	fmt.Printf("copied slice s2 :%v\n", s2)

	s3 := []int{1, 2, 3}
	fmt.Printf("slice s3 : %v\n", s3)
	s3 = append(s3, s2...) // 把 s3 加到  s2 上面
	fmt.Printf("appended slice s3 : %v\n", s3)
	s3 = append(s3, 4, 5, 6)
	fmt.Printf("last slice s3 : %v\n", s3)
}
